//
// Created by 董一龙 on 2022/10/13.
//

#include "mmaplib/mmap.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdexcept>
#include <sys/mman.h>
#include "mmaplib/platform/platform_interface.h"
#include "mmaplib/platform/mac/macos_adaptation.h"
//#include "fqueue/segment_queue/mmap_queue/buffer/mmaplib/platform/linux/linux_adaptation.h"
//#include "fqueue/segment_queue/mmap_queue/buffer/mmaplib/platform/win/windows_adaptation.h"

namespace fqueue {
    using platform = platform_interface<macos_adaptation>;
}
namespace fqueue::mmaplib {
    mmap::mmap(const std::string &filename, size_t mmap_size) {
        size_t file_size = platform::file_size(filename.c_str());
        if (file_size < mmap_size) {
            throw std::runtime_error("file is small");
        }
        m_addr = platform::mmap(NULL, mmap_size, PROT_READ|PROT_WRITE, MAP_SHARED, filename.c_str(), 0);
        if (m_addr == MAP_FAILED) {
            throw std::runtime_error("mmap fail");
        }
        m_size = mmap_size;
    }

    mmap::~mmap() {
        if (m_addr != nullptr) {
            platform::munmap(m_addr, m_size);
            m_addr = nullptr;
            m_size = 0;
        }
    }

    void *mmap::data() const {
        return m_addr;
    }

    size_t mmap::size() const {
        return m_size;
    }
} // fqueue::mmap